package com.cari.oa.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cari.oa.domain.SysActionEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.domain.SysLoginLogEntity;
import com.cari.oa.domain.SysModuleEntity;
import com.cari.oa.domain.SysRoleEntity;
import com.cari.oa.domain.SysUserEntity;
import com.cari.oa.service.NotificationService;
import com.cari.oa.service.SysActionService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysLoginLogService;
import com.cari.oa.service.SysModuleService;
import com.cari.oa.service.SysRoleService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
 * 登录controller
 * User: yexuhui
 * Date: 12-12-13
 * Time: 下午7:57
 */
@Controller
public class LoginController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysModuleService sysModuleService;
    @Resource
    private SysLoginLogService loginLogService;
    @Resource
    private SysActionService sysActionService;
    @Resource
    private SysRoleService sysRoleService;    
    @Resource
    private SysDictItemService sysDictItemService;
    @Resource
    private NotificationService notificationService;
    

    public static String USER_NAME_ATTR = "username";
    public static String USER_CNNAME_ATTR = "usercnname";
    public static String ACTION_URL_SET_ATTR = "actions";
    public static String PROVINCE_SET_ATTR = "provinces";
    
    public static int LOGIN_TYPE = 1;
    public static int LOGOUT_TYPE = 0;
    

    @RequestMapping(value = "/login.do", method = RequestMethod.GET)
    public String enterLogin(HttpSession session) {
        if(session.getAttribute(USER_NAME_ATTR) != null) return "redirect:/index.do";
        return "login";
    }

    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    @ResponseBody
    public String postLogin(String username, String password, String vericode, HttpServletRequest request) {
    	HttpSession session = request.getSession();
        if(session.getAttribute(USER_NAME_ATTR) != null) return Utils.normalJsonResp();

        if(StrUtils.isEmpty(username)) return Utils.errorJsonResp("用户名不能为空");
        if(StrUtils.isEmpty(password)) return Utils.errorJsonResp("密码不能为空");
        if(StrUtils.isEmpty(vericode)) return Utils.errorJsonResp("验证码不能为空");
        
        String sessVeriCode = (String) session.getAttribute(VeriCodeController.VERI_CODE_ATTR);
        if(!vericode.equals(sessVeriCode)) return Utils.errorJsonResp("验证码不正确");
        session.removeAttribute(VeriCodeController.VERI_CODE_ATTR);

        if(!sysUserService.existByEnname(username)) return Utils.errorJsonResp("找不到该用户");

        SysUserEntity sysUserEntity = sysUserService.getByNameAndPass(username, password);
        if(sysUserEntity == null) return Utils.errorJsonResp("密码不正确");

        session.setAttribute(USER_NAME_ATTR, username);
        session.setAttribute(USER_CNNAME_ATTR, sysUserEntity.getCnname());
        Set<String> actionSet = getActionSet(username);
        session.setAttribute(ACTION_URL_SET_ATTR, actionSet);
        Map<String, String>  provinceSet = getProvinceMap(username);
        session.setAttribute(PROVINCE_SET_ATTR, provinceSet);
        
        addLoginLog(username, Utils.getIp(request), LOGIN_TYPE);
        return Utils.normalJsonResp();
    }

    @RequestMapping("/logout.do")
    public String logout(HttpServletRequest request) {
    	HttpSession session = request.getSession(false);
    	if(session != null) {
	    	String username = (String)session.getAttribute(USER_NAME_ATTR);
	    	addLoginLog(username, Utils.getIp(request), LOGOUT_TYPE);
	        session.invalidate();
    	}
        return "redirect:login.do";
    }

    @RequestMapping("/index.do")
    public String index(ModelMap modelMap, HttpSession session) {
    	String username = (String)session.getAttribute(USER_NAME_ATTR);
        Map<String, List<SysModuleEntity>> subModuleMap = new HashMap<String, List<SysModuleEntity>>();
        Long unRead = notificationService.getListByToUser(username); //获取未读的通知
        List<SysModuleEntity> topModules = sysModuleService.getTopModulesByUser(username);
        List<SysModuleEntity> subModules = sysModuleService.getSubModulesByUser(username);
        for (SysModuleEntity module : subModules) {
        	List<SysModuleEntity> tmpModules = subModuleMap.get(module.getParentId());
        	if(tmpModules == null) {
        		tmpModules = new ArrayList<SysModuleEntity>();
        		subModuleMap.put(module.getParentId(), tmpModules);
        	}
        	tmpModules.add(module);
        }

        modelMap.addAttribute("topModules", topModules);
        modelMap.addAttribute("unRead", unRead);
        modelMap.addAttribute("subModuleMap", subModuleMap);
        return "index";
    }
    
    private void addLoginLog(String username, String ip, int loginType) {
    	SysLoginLogEntity logEntity = new SysLoginLogEntity();
    	logEntity.setIp(ip);
    	logEntity.setType(loginType);
    	logEntity.setUserName(username);
    	loginLogService.insert(logEntity);
    }
    
    private Set<String> getActionSet(String username) {
    	List<SysRoleEntity> roleList = sysRoleService.getRolesByUserName(username);
        Set<String> actionSet = new HashSet<String>();
        for (SysRoleEntity sysRoleEntity : roleList) {
        	List<SysActionEntity> actionList = sysActionService.getActionsByRole(sysRoleEntity.getEnname());
        	for (SysActionEntity sysActionEntity : actionList) {
        		String actionUrl = sysActionEntity.getUrl().trim();
        		String[] urls = actionUrl.split(",");
        		for (String url : urls) {
            		if(!url.startsWith("/")) url = "/" + url;
    				actionSet.add(url);
				}

			}
		}	
        return actionSet;
	}
    
    private Map<String, String> getProvinceMap(String username) {
    	SysUserEntity user = sysUserService.getByEnname(username);
        Set<String> provinceSet = new HashSet<String>();
        	if(StrUtils.isNotEmpty(user.getProvince())){
        		String[] provinces = user.getProvince().split(",");
        		for (String province : provinces) {
        			provinceSet.add(province);
				}
        	}
        	
    	List<SysDictItemEntity> pList = sysDictItemService.getItemsByGroupName("province");
    	Map<String, String> provinceMap = new TreeMap<String, String>();
        for (SysDictItemEntity item : pList) {
			if(provinceSet.contains(item.getValue()))provinceMap.put(item.getValue(), item.getName());
		 }
        return provinceMap;
	}
}
